<template>
  <div class="sign-container">
    <h2>部门签到统计</h2>
    <div class="month-selector">
      <el-date-picker
        v-model="currentMonth"
        type="month"
        placeholder="选择月份"
        @change="getSignList"
      />
    </div>
    
    <div class="tree-container">
      <el-tree
        :data="treeData"
        :props="treeProps"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :highlight-current="true"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <span class="node-label">{{ node.label }}</span>
            
            <template v-if="!data.isDept">
              <el-tag type="success" size="small" class="count-tag">
                正常: {{ data.normalSignInCount }}
              </el-tag>
              <el-tag type="danger" size="small" class="count-tag">
                异常: {{ data.abnormalSignInCount }}
              </el-tag>
              <el-tag type="info" size="small" class="count-tag">
                总计: {{ data.normalSignInCount + data.abnormalSignInCount }}
              </el-tag>
              <el-button 
                  size="small" 
                  type="primary" 
                  class="detail-btn"
                  @click="openSignDetail(data, formatMonth(currentMonth))"
                >
                  详情
                </el-button>
            </template>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
  <SignDetail ref="signDetailRef" @upd-ok="handleRefresh" />
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElTag, ElButton } from 'element-plus'
import req from '@/request'

//打开子组件
const openSignDetail = (data, month) => {
  signDetailRef.value.open(data, month)
}

const SignList = ref([])
const currentMonth = ref(new Date())
// 处理刷新逻辑
const handleRefresh = () => {
  getSignList()  // 直接调用获取签到列表的方法
}

//详情
import SignDetail from './SignDeatil.vue'

const signDetailRef = ref(null);

// 将原始数据转换为树形结构
const treeData = computed(() => {
  return SignList.value.map((dept, index) => ({
    id: `dept-${index}`,
    label: dept.deptName,
    isDept: true,
    children: dept.clockOverviewVos.map((employee, empIndex) => ({
      id: `emp-${index}-${empIndex}`,
      label: employee.userName || '部门统计',
      normalSignInCount: employee.normalSignInCount,
      abnormalSignInCount: employee.abnormalSignInCount,
      isDept: false,
      userId: employee.userId, // 添加用户ID，用于详情查询
      deptId: dept.deptId // 添加部门ID，用于详情查询
    }))
  }))
})

// 默认展开第一个部门
const defaultExpandedKeys = computed(() => {
  return treeData.value.length > 0 ? [treeData.value[0].id] : []
})

const treeProps = {
  children: 'children',
  label: 'label'
}


// 获取考勤记录
const getSignList = async () => {
  try {
    const params = {
      month: formatMonth(currentMonth.value)
    }
    const res = await req.get('/clockLogs/monthly', { params })
    SignList.value = res.data || []
  } catch (error) {
    console.error('获取考勤数据失败', error)
    ElMessage.error('获取考勤记录失败')
  }
}

const formatMonth = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
}

onMounted(() => {
  getSignList()
})
</script>

<style scoped>
.sign-container {
  padding: 20px;
}

.month-selector {
  margin-bottom: 20px;
}

.tree-container {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
}

.node-label {
  flex: 1;
}

.count-tag {
  margin-left: 10px;
}

.detail-btn {
  margin-left: 10px;
}

/* 调整树节点的间距 */
.el-tree {
  --el-tree-node-hover-bg-color: #f5f7fa;
}

.el-tree-node__content {
  height: 40px;
}
</style>